package com.ssyc.student.activity;

import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.NoScrollViewPager;
import com.ssyc.student.R;
import com.ssyc.student.bean.PrepareDetectionInfo;
import com.ssyc.student.fragment.StudentChooseAnserDetectionFramgent;
import com.ssyc.student.fragment.StudentPrepareDetectionCommitFragment;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--预习检测界面
 * Created by Administrator on 2018/5/25 0025.
 */

public class StudentPrepareDetectionActivity extends BaseActivity implements View.OnClickListener {

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";


    //更新的标识和重做的标识
    public static final int UPDATETYPE = 100;
    public static final int REFORMTYPE = 101;


    //加载框布局
    private RelativeLayout rlLoading;

    //返回
    private ImageView ivBack;

    //文章的标题
    private TextView tv__article_title;

    //文章的内容
    private TextView tv_article_content;

    //ViewPager页面
    private NoScrollViewPager vp;

    //模拟的题目
    private String topic;

    //定义的下划线的替换符号,5个空
    public static String regStr = "_____";

    //用于保存替换下划线为选择答案的map
    public static Map<Integer, String> underLineMap;

    //用于填充Vp的Framgent
    private List<Fragment> mFragments;

    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //使用填空二字切割服务器返回的题目内容获取的字符串数组
    private String[] contents;


    //A到Z的数据集合
    private String[] chartNums;

    //变红色的位置数
    private static final int count = 5;

    //课程的LessonId在提交界面可能需要该值,页面传递过来
    private String lessonId;

    //gradeId
    private String gradeId;


    //记录用户保存的时间
    public static long firstTime;

    //用于上传服务器记录时间的id
    private String rowId;

    //精力值
    private String energy;
    private PrepareDetectionInfo.DataBean.QuestionListBean questionListBean;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_student_prepare_detection;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //获取传递的数据
        initIntent();

        //请求服务器获取页面数据
        http();
    }


    //静态代码块
    {
        //初始化存放填空位置的内容的map
        underLineMap = new LinkedHashMap<>();

        //记录用户第一次进入的时间
        firstTime = System.currentTimeMillis();

        //初始化计时器
        TimeCount.init();

    }

    /**
     * 提供给Framgent获取map的方法
     *
     * @return
     */
    public static Map<Integer, String> getUnderLineMap() {
        return underLineMap;
    }


    /**
     * 提供获取第一次进入时间的方法
     *
     * @return
     */
    public static long getFirstTime() {
        return firstTime;
    }

    /**
     * 初始化视图
     */
    public void initView() {

        //获取A到Z的字母数组
        chartNums = getResources().getStringArray(R.array.base_letters);
        rlLoading = findViewById(R.id.rl_loading_view);
        rlLoading.setVisibility(View.VISIBLE);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tv__article_title = findViewById(R.id.tv__article_title);
        tv_article_content = findViewById(R.id.tv_article_content);
        vp = findViewById(R.id.vp);
        //初始进入允许滑动
        vp.setPagerEnabled(true);
    }


    /**
     * 获取传递的数据
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);
    }


    /**
     * 请求服务器获取页面数据的方法
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "20");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lesson", "Lesson" + lessonId);
        map.put("examtype", "12");
        map.put("role", AccountUtils.getRole(this));

        HttpUtils.post(HttpAdress.PERPAREDETECTION, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    if (null != rlLoading) {
                        rlLoading.setVisibility(View.GONE);
                    }
                    PrepareDetectionInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, PrepareDetectionInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            PrepareDetectionInfo.DataBean data = info.getData();
                            if (null != data) {
                                List<PrepareDetectionInfo.DataBean.QuestionListBean> question_list = data.getQuestion_list();

                                if (null != question_list && question_list.size() != 0) {
                                    //预习检测就一个题目,取第0个元素
                                    questionListBean = question_list.get(0);
                                    if (null != questionListBean) {

                                        //设置标题的数据
                                        setQuestionTitle(data.getBigtitle());

                                        //设置文章的内容
                                        setContent(questionListBean);

                                        //初始化填充的Framgent
                                        initFragments(questionListBean);

                                        //设置Vp
                                        initVp();
                                    }
                                }
                            }

                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("服务器异常", false);
                            Log.i("test", "返回异常码是:" + info.getState());
                        }
                    }
                }
            }
        });

    }

    /**
     * 设置文章标题
     *
     * @param title
     */
    private void setQuestionTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            tv__article_title.setText(title);
        }
    }

    /**
     * 设置文章内容
     * 用下划线替代"填空"后进行回显
     *
     * @param questionListBean
     */
    private void setContent(PrepareDetectionInfo.DataBean.QuestionListBean questionListBean) {

        //不可能以出现以填空开头
        String questionContent = questionListBean.getWordname();

        if (!TextUtils.isEmpty(questionContent)) {

            //切割字符串
            contents = questionContent.split("填空");

            //初始化Map,给每个需要替换下划线的值都初始为空串
            if (!questionContent.endsWith("填空")) {
                //不以填空结尾
                for (int i = 0; i < contents.length - 1; i++) {
//                    underLineMap.put(i, "");
                    underLineMap.put(i, regStr);
                }
            } else {
                //以填空结尾
                for (int i = 0; i < contents.length; i++) {
//                    underLineMap.put(i, "");
                    underLineMap.put(i, regStr);
                }
            }

//            Log.i("test", "underLineMap的长度是: " + underLineMap.size());

            //将填空全部替换成下划线
            tv_article_content.setText(questionContent.replace("填空", regStr));
        }
    }

    /**
     * 初始化Fragment的操作
     */
    private void initFragments(PrepareDetectionInfo.DataBean.QuestionListBean question) {

        mFragments = new ArrayList<>();

        //将该question对象直接传递给Framgent页面
        mFragments.add(StudentChooseAnserDetectionFramgent.newInstance(question));

        //提交
        mFragments.add(StudentPrepareDetectionCommitFragment.newInstance(question, lessonId, gradeId));
    }

    /**
     * 设置Vp
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * 处理通讯事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (busInfo != null && busInfo.getType() == 4) {

            //表示收到了更新页面填空题显示的事件
            //获取选择答案的位置
            int pos = busInfo.getPos();

            //回显需要显示的选择答案的序列号,注意这里一定是要2个空格+序号+2个空格,跟替换的5个下划线长度保持一致
            String chooseAnswerNum = "  " + chartNums[pos] + "  ";

            //拼接需要回显的答案,首先需要判断保存的下划线map中空串的位置
            for (int i = 0; i < underLineMap.size(); i++) {
                if (TextUtils.isEmpty(underLineMap.get(i)) || regStr.equals(underLineMap.get(i))) {
                    //保存或者替换第一个Map没有保存的值
                    underLineMap.put(i, chooseAnswerNum);
                    break;
                }
            }

            Log.i("test", "选择的答案是 " + chooseAnswerNum);

            //重新设置文本的值
            setShowContent(true);

            //这里是接受到用户选择答案后改变Map的存值后在发送重做消息给用户提交答案的Fragment界面
            BusInfo reformInfo = new BusInfo();
            reformInfo.setType(REFORMTYPE);
            EventBus.getDefault().post(reformInfo);

        } else if (busInfo != null && StudentShowPrepareDetectionAnswerActivity.LOOKANSWER == busInfo.getType()) {
            //收到查看答案的消息,让Vp显示第一页
            vp.setCurrentItem(0);
            //让展示题目的TextView不可交互
            tv_article_content.setEnabled(false);
            //让ViewPager不可滑动
            vp.setPagerEnabled(false);
        } else if (busInfo != null && StudentShowPrepareDetectionAnswerActivity.CLOSE == busInfo.getType()) {
            //关闭页面的消息
            finish();
        } else if (busInfo != null && StudentChooseAnserDetectionFramgent.VPSCROLL == busInfo.getType()) {
            //翻页的操作
            vp.setCurrentItem(1);
        }
    }

    /**
     *
     * contents=["1","2","3","4];
     * 不以填空结尾,underLineMap的长度比contents的长度要少1
     * underLinMap={"0":_____,"1":_____,"2":______}
     * 以填空结尾,underLineMap的长度比contents的长度相同
     * underLinMap={"0":_____,"1":_____,"2":______,"3":_____}
     */

    /**
     * 重新设置文本的值
     */
    private void setShowContent(boolean isflag) {

        //取值,定义需要回显的问题
        StringBuffer sb = new StringBuffer();

        if (questionListBean.getWordname().endsWith("填空")) {
            //以填空结尾
            //此时要回显的内容
            for (int i = 0; i < contents.length; i++) {
                //添加分割的数组内容
                sb.append(contents[i]);
                if (!TextUtils.isEmpty(underLineMap.get(i))) {
                    //当前下划线有值,添加2个空格+当前位置的值+2个空格,一共5个字符
                    sb.append(underLineMap.get(i));
                } else {
                    //当前下划线没有值,添加5个下划线
                    sb.append(regStr);
                }
            }

        } else {
            //不以填空结尾,underLinemap长度是4,contents长度是5
            for (int i = 0; i < underLineMap.size(); i++) {
                //添加分割的数组内容
                sb.append(contents[i]);
                if (!TextUtils.isEmpty(underLineMap.get(i))) {
                    //当前下划线有值,添加2个空格+当前位置的值+2个空格,一共5个字符
                    sb.append(underLineMap.get(i));
                } else {
                    //当前下划线没有值,添加5个下划线
                    sb.append(regStr);
                }
            }
            sb.append(contents[contents.length - 1]);
        }

        //获取需要回显的题目内容
        String showTopics = sb.toString();
        Log.i("test", "内容是:" + showTopics);

        SpannableStringBuilder content = new SpannableStringBuilder(showTopics);

        //设置回显的题目内容的文字变红,下划线以及需要点击的文字
        //计算文字变红和下划线的位置的方法
        //0个位置  contents[0].length()
        //1个位置  contents[0].length() +contents[1].length()+underLineMap.get(0).length()
        //2个位置  contents[0].length() +contents[1].length()+contents[2].length()+underLineMap.get(0).length()+underLineMap.get(1).length()
        //需要做的操作时,将content中所有underLineMap位置的值标红并添加下划线
        for (int i = 0; i < underLineMap.size(); i++) {
            int start = 0;
            if (i == 0) {
                start = contents[0].length();
            } else {
                for (int j = 0; j <= i; j++) {
                    start += contents[j].length();
                }
                for (int k = 0; k <= i - 1; k++) {
                    start += underLineMap.get(k).length();
                }
            }

            if (!TextUtils.isEmpty(underLineMap.get(i))) {
                //设置文字变色和下划线的方法
                setTextViewState(isflag, i, content, start);
            }
        }

//        if (questionListBean.getWordname().endsWith("填空")) {
//            //以填空结尾,此时underLineMap的长度跟contents的长度一致
//            for (int i = 0; i < underLineMap.size(); i++) {
//                //需要做的操作时,将content中所有underLineMap位置的值标红并添加下划线
//                int start = 0;
//                if (i == 0) {
//                    start = contents[0].length();
//                } else {
//                    for (int j = 0; j <= i; j++) {
//                        start += contents[j].length();
//                    }
//                    for (int k = 0; k <= i - 1; k++) {
//                        start += underLineMap.get(k).length();
//                    }
//                }
//
//                if (!TextUtils.isEmpty(underLineMap.get(i))) {
//                    //设置文字变色和下划线的方法
//                    setTextViewState(isflag, i, content, start);
//                }
//            }
//
//        } else {
//            //不以填空结尾,此时underLineMap的长度比contents的长度少1
//            for (int i = 0; i < underLineMap.size(); i++) {
//                int start = 0;
//                if(i==0){
//                    //第一个位置
//                    start = contents[0].length();
//                }else{
//
//                    for (int j = 0; j <= i; j++) {
//                        start += contents[j].length();
//                    }
//                    for (int k = 0; k <= i - 1; k++) {
//                        start += underLineMap.get(k).length();
//                    }
//
//
//                }
//
//                if (!TextUtils.isEmpty(underLineMap.get(i))) {
//                    //设置文字变色和下划线的方法
//                    setTextViewState(isflag, i, content, start);
//                }
//            }
//        }

        //设置答案
        tv_article_content.setText(content);
    }


    /**
     * 设置文字变色的方法和加下划线的方法
     *
     * @param content
     * @param start
     */

    private void setTextViewState(boolean isFlag, int pos, SpannableStringBuilder content, int start) {

        ForegroundColorSpan colorSpan = null;

        if (isFlag) {
            colorSpan = new ForegroundColorSpan(Color.parseColor("#FF0000"));
        } else {
            colorSpan = new ForegroundColorSpan(Color.parseColor("#A3A3A3"));
        }

        content.setSpan(colorSpan, start, start + count, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        content.setSpan(new UnderlineSpan(),
                start, start + count, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        //设置点击事件
        content.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                //通过EventBus通知Fragment界面进行答案选项重置,这里点击当前位置后清除选择的答案的同时需要告知
                //Fragment界面的可选择答案的状态重置,变成可选择的状态
                BusInfo info = new BusInfo();
                info.setType(UPDATETYPE);
                info.setPos(pos);
                EventBus.getDefault().post(info);

                //重新点击后改变Map当前存放的值为
                underLineMap.put(pos, regStr);
                setShowContent(true);

                //发送重做消息给用户提交答案的Fragment界面
                BusInfo reformInfo = new BusInfo();
                reformInfo.setType(REFORMTYPE);
                EventBus.getDefault().post(reformInfo);

            }
        }, start, start + count, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        //设置该方法后,点击事件才能生效
        tv_article_content.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * 页面控件的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        }

    }


    /**
     * 该生命周期内请求服务器记录初次进入的时间
     */
    @Override
    protected void onResume() {
        super.onResume();
        RecordTimeUtil.httpEnterTime(this, lessonId, gradeId, "12", new RecordTimeUtil.onRecordRowIdListener() {
            @Override
            public void recordRowId(String id, String en) {
                rowId = id;
                energy = en;
                Log.i("test", "en的值是:" + en);
            }
        });
    }

    /**
     * 熄屏
     */
    @Override
    protected void onPause() {
        super.onPause();

        long time = System.currentTimeMillis() - TimeCount.newInstance().getLastTime();

        //计算总用时
        long totalTime = TimeCount.newInstance().getTotalTime() + time;

        //记录总用时
        TimeCount.newInstance().setTotalTime(totalTime);

        //上传服务器记录时间的接口
        RecordTimeUtil.httpExitTime(rowId, this);
    }


    /**
     * 考虑亮屏
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        //重置LastTime
        TimeCount.newInstance().setLastTime(System.currentTimeMillis());
    }

}
